package org.totalbeginner.tutorial;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class MyUtilities {

	public static boolean saveStringToFile(String fileName, String szToSave) {
		boolean bSaved = false;
		
		if(fileName.isEmpty() || szToSave.isEmpty())
			return bSaved;
		
		BufferedWriter bw = null;
		try{
			
			bw = new BufferedWriter(new FileWriter(fileName));
			
			try{
				bw.write(szToSave);
				bSaved = true;
			}
			finally{
				bw.close();
			}
		}
		catch(IOException ex){
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
		return bSaved;
	}

	public static String getStringFromFile(String fileName) {
		StringBuffer szToReturn = new StringBuffer();
		BufferedReader br = null;
		try{
			br = new BufferedReader(new FileReader(fileName));
			try{
				String szLine = "";
				while((szLine=br.readLine())!=null){
					szToReturn.append(szLine);
					szToReturn.append('\n');
				}
			}
			finally{
				br.close();
			}
		}
		catch(IOException ex){
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
		return szToReturn.toString();
	}

	public static String convertToXML(MyLibrary myLibStart) {
		XStream xs = new XStream(new DomDriver());
		return xs.toXML(myLibStart);
	}

	public static MyLibrary convertFromXML(String szXMLMyLib) {
		XStream xs = new XStream(new DomDriver());
		MyLibrary myLib = null;
		Object obj = xs.fromXML(szXMLMyLib);
		if(obj instanceof MyLibrary)
			myLib = (MyLibrary)obj;
		return myLib;
	}

	public static boolean saveMyLibrary(String szFileName, MyLibrary myLibStart) {
		return saveStringToFile(szFileName, convertToXML(myLibStart));
	}

	public static MyLibrary loadMyLibrary(String szfileName) {
		return convertFromXML(getStringFromFile(szfileName));
	}

}
